package tum0r.webengine.models.utils.vercode

/**
 * 说明: 生成算数验证码
 *
 * 创建者: tum0r
 *
 * 时间: 2021/8/29 19:59
 *
 * @param[pointDivide] 干扰点除以的数字
 * @param[lineCount] 干扰线数目
 */
class ExpressionVerificationCode(pointDivide: Int = 8, lineCount: Int = 6) : VerificationCodeBase(2, pointDivide, lineCount) {
    /**
     * 算数数字的起始
     */
    private var startNumber: Int = -100
    /**
     * 算数数字的结束
     */
    private var endNumber: Int = 100

    override fun generateCode(): String {
        val result = StringBuilder()
        var answer = 0
        val number1 = random.nextInt(endNumber - startNumber) + startNumber
        val number2 = random.nextInt(endNumber - startNumber) + startNumber
        result.append(number1)
        if (random.nextBoolean()) result.append(" ")
        val op = random.nextInt(3)
        when (op) {
            0 -> result.append("+")
            1 -> result.append("-")
            2 -> result.append("x")
        }
        when (op) {
            0 -> answer = number1 + number2
            1 -> answer = number1 - number2
            2 -> answer = number1 * number2
        }
        result.append(" ")
        result.append(number2)
        if (random.nextBoolean()) result.append(" ")
        result.append("=")
        if (random.nextBoolean()) result.append(" ")
        result.append("?").append(answer)
        return result.toString()
    }

    override fun newCode(code: String, answer: String) {
        val normalVerificationCode = NormalVerificationCode()
        normalVerificationCode.newCode(code, answer)
        this.answer = normalVerificationCode.answer
        this.codeImage = normalVerificationCode.codeImage
    }

    override fun newCode() {
        val code = generateCode().split("?")
        newCode("${code[0]}?", code[1])
    }
}